package com.example.lenovo.asia5b.home.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.example.lenovo.asia5b.commodity.activity.ClassifyMainSonActivity;
import com.example.lenovo.asia5b.commodity.activity.CommodityDetActivity;
import com.example.lenovo.asia5b.commodity.bean.ClassifyMainSonBean;
import com.example.lenovo.asia5b.home.activity.WebViewActivity;
import com.example.lenovo.asia5b.home.adapter.NewProductsAdapter;
import com.example.lenovo.asia5b.home.bean.WellKonwnBean;
import com.example.lenovo.asia5b.ui.DownloadPicture;
import com.example.lenovo.asia5b.ui.LoadingDalog;
import com.example.lenovo.asia5b.util.DensityUtil;
import com.example.lenovo.asia5b.util.ICallBack;
import com.example.lenovo.asia5b.util.JsonTools;
import com.example.lenovo.asia5b.util.Logic;
import com.example.lenovo.asia5b.util.Setting;
import com.jude.rollviewpager.OnItemClickListener;
import com.jude.rollviewpager.RollPagerView;
import com.jude.rollviewpager.adapter.StaticPagerAdapter;
import com.jude.rollviewpager.hintview.ColorPointHintView;
import com.wushi.lenovo.asia5b.R;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import app.BaseFragment;
import fay.frame.ui.U;

/**
 * 新品推荐
 * Created by lenovo on 2017/6/29.
 */

public class MainNewProductsFragment extends BaseFragment implements ICallBack {

    private View fragmentView;
    private View header;
    private View botton;
    private ListView listView;
    private NewProductsAdapter adapter;
    private RollPagerView mRollViewPager;//图片轮播
    private int page  = 1;
    private int countPage = 0;
    private GridView gridView;
    private int width;
    private List<WellKonwnBean> wellKonwnList = null;
    private List<Map<String,String>> list_imag = new ArrayList<Map<String,String>>();
    private LoadingDalog loadingDalog;
    private List<ClassifyMainSonBean> lists = null;
    private List<ClassifyMainSonBean> listsTwo = null;
    private Button btn_quality_goods,btn_new_goods;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        fragmentView = (View) inflater.inflate(R.layout.frame_new_products, null);
        width = DensityUtil.getScreenWidth(getActivity());
        initView();
        initRollViewPager();
        newAdData();
        goodsNewData();
        goodsBoutiqueData();
        return fragmentView;
    }

    private void initView() {
        getPostAPI();
        loadingDalog = new LoadingDalog(getActivity());
        loadingDalog.show();
        adapter = new NewProductsAdapter(getActivity());
        listView = (ListView) fragmentView.findViewById(R.id.frame_new_products_lv);
        header = LayoutInflater.from(getActivity()).inflate(R.layout.frame_new_products_header, null);
        btn_quality_goods = (Button)header.findViewById(R.id.btn_quality_goods);
        btn_new_goods = (Button)header.findViewById(R.id.btn_new_goods);
        btn_quality_goods.setOnClickListener(this);
        btn_new_goods.setOnClickListener(this);
        listView.addHeaderView(header);

        botton = LayoutInflater.from(getActivity()).inflate(R.layout.frame_new_products_botton, null);
        gridView = (GridView) botton.findViewById(R.id.well_known_gv);
        gridView.setVisibility(View.GONE);
        //设置gridView高度
        gridView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT , width*2/3));
        listView.addFooterView(botton);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (i >= 1) {
                    if(adapter.getLists()!=null && adapter.getLists().size()>0) {
                        if (i<= adapter.getLists().size()) {
                            ClassifyMainSonBean bean = adapter.getLists().get(i - 1);
                            Intent intent = new Intent(getActivity(), CommodityDetActivity.class);
                            intent.putExtra("goods_id", bean.goods_id);
                            startActivity(intent);
                        }
                    }
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_quality_goods:
                btn_quality_goods.setTextColor( ContextCompat.getColor(getActivity(),R.color.white));
                btn_quality_goods.setBackgroundColor( ContextCompat.getColor(getActivity(),R.color.my_999));
                btn_new_goods.setTextColor( ContextCompat.getColor(getActivity(),R.color.my_333));
                btn_new_goods.setBackgroundColor( ContextCompat.getColor(getActivity(),R.color.white));
                adapter.setLists(lists);
                adapter.notifyDataSetChanged();
                break;
            case R.id.btn_new_goods:
                btn_new_goods.setTextColor( ContextCompat.getColor(getActivity(),R.color.white));
                btn_new_goods.setBackgroundColor( ContextCompat.getColor(getActivity(),R.color.my_999));
                btn_quality_goods.setTextColor( ContextCompat.getColor(getActivity(),R.color.my_333));
                btn_quality_goods.setBackgroundColor( ContextCompat.getColor(getActivity(),R.color.white));
                adapter.setLists(listsTwo);
                adapter.notifyDataSetChanged();
                break;
            default:
                break;
        }
    }
    private void initRollViewPager() {
        //图片轮播
        mRollViewPager = (RollPagerView) header.findViewById(R.id.frame_new_products_roll_view_pager);
        //设置播放时间间隔
        mRollViewPager.setPlayDelay(3000);
        //设置透明度
        mRollViewPager.setAnimationDurtion(500);
        //设置适配器
        mRollViewPager.setAdapter(new TestNormalAdapter());
        mRollViewPager.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                Intent intent = null;
                Map map =list_imag.get(position);
                try {
                    JSONArray jsonArray = new JSONArray(map.get("ad_link").toString());
                    String type = jsonArray.getString(0);
                    if (type.equals("goods")) {
                        intent = new Intent(getActivity(), CommodityDetActivity.class);
                        intent.putExtra("goods_id",jsonArray.getString(1));
                        getActivity().startActivityForResult(intent,0);
                    }
                    else if (type.equals("cat_id")) {
                        intent = new Intent(getActivity(), ClassifyMainSonActivity.class);
                        intent.putExtra("catid",jsonArray.getString(1));
                        intent.putExtra("catname",jsonArray.getString(2));
                        startActivity(intent);
                    } else if (type.equals("promotion")) {
                        intent = new Intent(getActivity(), WebViewActivity.class);
                        intent.putExtra("url",jsonArray.getString(1));
                        startActivity(intent);
                    }
                } catch (Exception e) {

                }
            }
        });

        //设置指示器（顺序依次）
        //自定义指示器图片
        //设置圆点指示器颜色
        //设置文字指示器
        //隐藏指示器
        mRollViewPager.setHintView(new ColorPointHintView(fragmentView.getContext(), Color.YELLOW, Color.WHITE));
    }

    private void getPostAPI(){
        String apiUrl = Setting.WELLKNOWN;
        JsonTools.getJsonAll(this,apiUrl,null,0);
    }

    /**
     * 新品广告
     */
    public void newAdData() {
        Map<String, String> formMap = new HashMap<String, String>();
        formMap.put("adtype",""+"newFlash");
        String url = Setting.INDEX_FLASH;
        JsonTools.getJsonAll(this, url, formMap, 1);
    }

    /**
     * 精品推荐
     */
    public void goodsBoutiqueData() {
        Map<String, String> parmaMap = new HashMap<String, String>();
        String url = Setting.GOODS_NEW;
        parmaMap.put("page",""+page);
        parmaMap.put("type","2");
        JsonTools.getJsonAll(this, url, parmaMap, 2);
    }

    /**
     * 新品推荐
     */
    public void goodsNewData() {
        Map<String, String> parmaMap = new HashMap<String, String>();
        String url = Setting.GOODS_NEW;
        parmaMap.put("page",""+page);
        parmaMap.put("type","1");
        JsonTools.getJsonAll(this, url, parmaMap, 3);
    }

    private Handler handler2 = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            JSONObject result= null;
            try {
                result = new JSONObject(msg.obj.toString());
            } catch (Exception e) {
            }
            int action = msg.what;
            if (action == 0) {
                try{
                    if(result != null){
                        if(action == 0){
                            JSONObject jsonObject = (JSONObject)result;
                            JSONArray jsonArray = jsonObject.getJSONArray("mingzhan");
                            wellKonwnList = (List<WellKonwnBean>) Logic.getListToBean(jsonArray, new WellKonwnBean());
                            gridView.setAdapter(new WellKnownAdapter(getActivity(),width,wellKonwnList));
                            gridView.setVisibility(View.VISIBLE);
                        }
                    }
                }catch (Exception e){
                    Log.e("",e.getMessage());
                }
            } else if (action == 1) {
                if (null != result && result instanceof JSONObject) {
                    try {
                        JSONObject json =  (JSONObject)result;
                        int state = (int)json.getInt("State");
                        if (state == 0) {
                            JSONArray jsonArray = json.getJSONArray("images");
                            for (int i = 0; i < jsonArray.length(); i++) {
                                Map<String,String> map = new HashMap<String,String>();
                                JSONObject img  = jsonArray.getJSONObject(i);
                                map.put("ad_code",img.getString("ad_code"));
                                map.put("ad_link",img.getString("ad_link"));
                                list_imag.add(map);
                            }
                        }
                        initRollViewPager();
                    } catch (Exception e) {
                    }
                }
            }
            else if (action == 2) {
                if (null != result && result instanceof JSONObject) {
                    try {
                        JSONObject json =  (JSONObject)result;
                        int state = (int)json.getInt("State");
                        if (state == 0) {
                            JSONArray account = json.getJSONArray("goods");
                            lists = Logic.getListToBean(account,new ClassifyMainSonBean());
                            adapter.setLists(lists);
                            adapter.notifyDataSetChanged();
                        }  else if(state == 1){
                            U.Toast(getActivity(),"签名失败");
                        }else if(state == 2){
                            U.Toast(getActivity(),"参数错误");
                        }
                    } catch (Exception e) {
                    }
                }
                loadingDalog.dismiss();
            }else if (action == 3) {
                if (null != result && result instanceof JSONObject) {
                    try {
                        JSONObject json =  (JSONObject)result;
                        int state = (int)json.getInt("State");
                        if (state == 0) {
                            JSONArray account = json.getJSONArray("goods");
                            listsTwo = Logic.getListToBean(account,new ClassifyMainSonBean());
                        }  else if(state == 1){
                            U.Toast(getActivity(),"签名失败");
                        }else if(state == 2){
                            U.Toast(getActivity(),"参数错误");
                        }
                    } catch (Exception e) {
                    }
                }
            }

        }
    };

    @Override
    public void logicFinish(Object result, int action) {
        Message msg = new Message();
        msg.what = action;
        msg.obj = result.toString();
        handler2.sendMessage(msg);
    }

    class TestNormalAdapter extends StaticPagerAdapter {
        @Override
        public View getView(ViewGroup container, int position) {
            ImageView view = new ImageView(container.getContext());
            Map map = list_imag.get(position);
            DownloadPicture.loadNetwork(map.get("ad_code").toString(),view);
            view.setScaleType(ImageView.ScaleType.CENTER_CROP);
            view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            return view;
        }

        @Override
        public int getCount() {
            return list_imag.size();
        }
    }

    /**
     * 名店推荐
     */
    class WellKnownAdapter extends BaseAdapter {
        //上下文对象
        private Context context;
        private int width;
        private List<WellKonwnBean> wellKonwnList;
        private LayoutInflater mInflater;

        public WellKnownAdapter(Context context,int width,List list) {
            this.context = context;
            this.width = width / 3;
            this.wellKonwnList = list;
            this.mInflater = LayoutInflater.from(context);
        }

        public int getCount() {
            return wellKonwnList.size();
        }

        public Object getItem(int item) {
            return wellKonwnList.get(item);
        }

        public long getItemId(int id) {
            return id;
        }

        //创建View方法
        public View getView(int position, View convertView, ViewGroup parent) {
            ImageView imageView;
            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.itm_well_known, null);
                imageView = (ImageView)convertView.findViewById(R.id.image_head);
                imageView.setLayoutParams(new GridView.LayoutParams(width, width));
                //设置ImageView对象布局imageView.setAdjustViewBounds （false）; //设置边界对齐
                imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); //设置刻度的类型
            } else {
                imageView = (ImageView) convertView;
            }
            DownloadPicture.loadNetwork(wellKonwnList.get(position).ad_code,imageView); //为ImageView设置图片资源
            imageView.setOnClickListener(new ImageViewClick(position,wellKonwnList.get(position)));
            return imageView;
        }

        class ImageViewClick implements View.OnClickListener{

            private int index;
            private WellKonwnBean wellKonwnBean;

            public ImageViewClick(int index,WellKonwnBean wellKonwnBean){
                this.index = index;
                this.wellKonwnBean = wellKonwnBean;
            }

            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(),WebViewActivity.class);
                intent.putExtra("url",wellKonwnBean.ad_link);
                intent.putExtra("san","");
                startActivity(intent);
            }
        }
    }
}
